package com.itheima.a_cookie;

import com.itheima.utils.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@WebServlet("/LastTimeServlet")
public class LastTimeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取名称为LastTimeCookie对象
        Cookie[] cookies = request.getCookies();

        //遍历数组,查找LastTimeCookie对象
        Cookie cookie = CookieUtils.findCookieByName(cookies,"LastTimeCookie");

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter pw = response.getWriter();

        //判断cookie是否为null
        if (cookie == null){
            //是首次访问
            pw.write("<h4>欢迎您首次访问!</h4>");
        }else {
            //不是首次访问
            //获取Cookie中的值
            String time = cookie.getValue();
            pw.write("<h4>欢迎您回来,您上次的访问时间:" + time + "!</h4>");
        }

        /*
            4. 无论是否是第一次访问, 使用Cookie记录当次的访问时间
            注意:
                Cookie中不能存储空格
                tomcat8可以存储中文
         */
        Cookie ck = new Cookie("LastTimeCookie", new Date().toLocaleString().replaceAll(" ", ""));


        // 设置Cookie持久化时间
        ck.setMaxAge(24 * 60 * 60);

        // 返回浏览器保存
        response.addCookie(ck);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
